#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
// ./a.out ./a ./b

typedef struct
{
    char srcDirName[256];
    char fileName[256];
    char destDirName[256];
} CopyData_t;

void *copyFile(void *arg)
{

    CopyData_t *copyData = (CopyData_t *)arg;
    printf("\n拷贝文件 %s.............\n", copyData->fileName);
    char srcPath[1024] = {0};
    char destPath[1024] = {0};
    sprintf(srcPath, "%s/%s", copyData->srcDirName, copyData->fileName);
    sprintf(destPath, "%s/%s", copyData->destDirName, copyData->fileName);

    FILE *srcFile = fopen(srcPath, "r");
    if (srcFile == NULL)
    {
        printf("打开源文件失败\n");
        return NULL;
    }

    FILE *destFile = fopen(destPath, "w");
    if (destFile == NULL)
    {
        printf("打开目标文件失败\n");
        return NULL;
    }

    char buf[1024] = {0};
    int len = 0;
    while ((len = fread(buf, 1, 1024, srcFile)) > 0)
    {
        fwrite(buf, 1, len, destFile);
    }
    fclose(srcFile);
    fclose(destFile);
    printf("拷贝文件 %s 完成\n", copyData->fileName);
    return NULL;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("参数错误\n");
        return 0;
    }

    DIR *srcDir = opendir(argv[1]);
    if (srcDir == NULL)
    {
        printf("打开目录失败\n");
        return 0;
    }

    DIR *destDir = opendir(argv[2]);
    if (destDir == NULL)
    {
        if (errno == ENOENT)
        {
            if (mkdir(argv[2], 0777) != 0)
            {
                perror("mkdir");
            }
        }
        else
        {
            printf("打开目录失败\n");
            return 0;
        }
    }

    pthread_t tid[1024];
    int index = 0;

    // 拷贝目录
    while (1)
    {
        struct dirent *dir = readdir(srcDir);
        if (dir == NULL)
        {
            break;
        }

        if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0)
        {
            continue;
        }

        if (dir->d_type == DT_REG) // 普通文件
        {
            static CopyData_t data[1024] = {0};
            strcpy(data[index].fileName, dir->d_name);
            strcpy(data[index].destDirName, argv[2]);
            strcpy(data[index].srcDirName, argv[1]);

            pthread_create(&tid[index], NULL, copyFile, &data[index]);

            index++;

            printf("遍历到:%s文件 ，创建线程[%ld]处理,目前线程数量:%d\n", dir->d_name, tid[index], index);
        }
    }

    closedir(srcDir);
    closedir(destDir);

    for (int i = 0; i < index; i++)
    {
        pthread_join(tid[i], NULL);
    }

    return 0;
}